package com.bootdo.wx.api;

import com.bootdo.common.utils.*;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.*;
import com.github.pagehelper.PageInfo;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.apache.http.util.EntityUtils;


/**
 * Created by HP on 2019/5/28.
 */

@Controller
@RequestMapping("/api/member")
public class ApiMemberController {

    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private MemberAddressService memberAddressService;
    @Autowired
    private SetWechatService setWechatService;
    @Autowired
    private MemberTokenService memberTokenService;
    @Autowired
    private MemberFeedbackService memberFeedbackService;
    @Autowired
    private MemberSignService memberSignService;




    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     *
     * @Title:
     * @Description: 修改个人信息
     * @param map
     * @return R
     * @author Administrator
     * @date 2018年9月27日上午10:31:23
     */
    @RequestMapping("/editUser")
    @ResponseBody
    public R editUser(@RequestBody Map<String, Object> map) {
        if (!map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString()) ||
                !map.containsKey("phone") || StringUtils.isBlank(map.get("phone").toString()) ||
                !map.containsKey("wechat") || StringUtils.isBlank(map.get("wechat").toString())
        ){
            return R.error("参数错误");
        }
        try {
            MemberUserDO user = new MemberUserDO();
            user.setPhone(map.get("phone").toString());   //联系方式
            user.setId(map.get("userId").toString());
            user.setWechat(map.get("wechat").toString());   //微信号
            memberUserService.update(user);
            return R.ok();
        } catch (Exception e) {
            return R.error("操作失败");
        }
    }

    /**
     * 查询个人收货地址
     */
    @PostMapping( "/address/list")
    @ResponseBody
    public R addressList(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")){
            return R.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            List<MemberAddressDO> list = memberAddressService.queryByUserId(params);
            return R.ok().put("data", list);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }


    /**
     * 添加收货地址
     */
    @PostMapping( "/address/add")
    @ResponseBody
    public R addressAdd(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||!params.containsKey("province")
                ||!params.containsKey("city")||!params.containsKey("county")
                ||!params.containsKey("address")
                ||!params.containsKey("fullName")||!params.containsKey("phone")
                ||!params.containsKey("default")
                ){
            return R.error("参数异常");
        }
        try{
//			String userId = params.get("userId").toString();
            memberAddressService.add(params);
            return R.ok();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }
    /**
     * 修改收货地址
     */
    @PostMapping( "/address/change")
    @ResponseBody
    public R addressChange(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("province")
                ||!params.containsKey("city")||!params.containsKey("county")
                ||!params.containsKey("address")||!params.containsKey("userId")
                ||!params.containsKey("fullName")||!params.containsKey("phone")
                ||!params.containsKey("default")
                ){
            return R.error("参数异常");
        }
        try{
            memberAddressService.change(params);
            return R.ok();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 删除收货地址
     */
    @PostMapping( "/address/remove")
    @ResponseBody
    public R addressRemove(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            String addressId = params.get("addressId").toString();
            MemberAddressDO addressDO = memberAddressService.get(addressId);
            if (!userId.equals(addressDO.getUserId())){
                return R.error("收货地址异常");
            }
            memberAddressService.remove(addressId);
            return R.ok("删除成功");
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 设置默认收货地址
     */
    @PostMapping( "/address/default")
    @ResponseBody
    public R addressDefault(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            return memberAddressService.toDefault(params);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 获取收货地址详情
     */
    @PostMapping( "/address/getById")
    @ResponseBody
    public R getById(@RequestBody Map<String, Object> params){
        if (!params.containsKey("addressId")||!params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            String addressId = params.get("addressId").toString();
            MemberAddressDO addressDO = memberAddressService.get(addressId);
            return R.ok().put("data", addressDO);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 获得默认收货地址
     */
    @PostMapping("/address/getDefault")
    @ResponseBody
    public R getDefault(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||!params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            params.put("defaultValue","0");
            params.put("delFlag","0");
            List<MemberAddressDO> list = memberAddressService.list(params);
            if (list.size() != 0) {
                return R.ok().put("data",list.get(0));
            } else {
                return R.ok();
            }
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 个人中心
     */
    @PostMapping("/getMemberCenter")
    @ResponseBody
    public R getMemberCenter(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            Map<String,Object> map = memberUserService.getMemberCenter(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 我的粉丝
     * type:1：一级粉丝，2：二级粉丝，3：所有
     */
    @PostMapping("/getMyFans")
    @ResponseBody
    public R getMyFans(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("type") || !params.containsKey("type")
                ){
            return R.error("参数异常");
        }
        try{
            PageInfo<Map<String,Object>> map = memberUserService.getMyFans(params);
            return R.ok().put("data",map);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 获取小程序 key
     */
    @GetMapping("/getKey")
    @ResponseBody
    public R getKey(){
        try{
            Map<String,Object> paramsMap = new HashMap<String,Object>();
            paramsMap.put("delFlag","0");
            SetWechatDO setWechatDO = setWechatService.list(paramsMap).get(0);
            return R.ok().put("data",setWechatDO);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 微信用户授权  开始获取用户信息
     * @param
     * @return
     */
    @RequestMapping("/user/getUserInfo")
    @ResponseBody
    public R getUserInfo(@RequestBody Map<String, Object> map) {
        log.error("开始微信授权登录：" + map.toString());
        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("delFlag","0");
        SetWechatDO setWechatDO = setWechatService.list(paramsMap).get(0);
        String appid = setWechatDO.getAppId();
        String appsecret = setWechatDO.getAppSecret();
        try {
            //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
            //////////////// ////////////////
            // 请求参数
            String params = "appid=" +  appid + "&secret=" + appsecret + "&js_code=" + map.get("code").toString() + "&grant_type="
                    + "authorization_code";
            // 发送请求
            Response response = HttpUtils.get("https://api.weixin.qq.com/sns/jscode2session?" + params);
            String sr = java.net.URLDecoder.decode(response.body(), "utf-8");
            // 解析相应内容（转换成json对象）
            JSONObject json = JSONObject.parseObject(sr);
            log.error("授权登录请求json："+json);
            // 获取会话密钥（session_key）
            String session_key = json.getString("session_key").replace(" ", "+");
            // 用户的唯一标识（openid）
            String openid = json.getString("openid");
            //查看表里有没有这个用户
            MemberUserDO memberUserDO = memberUserService.queryByOpenid(openid);
            if(memberUserDO==null){
                ////////////////2、对encryptedData加密数据进行AES解密 ////////////////
                String decrypts = AesCbcUtil.decrypt(map.get("encryptedData").toString(), session_key,
                        map.get("iv").toString(), "UTF-8");
                if (null != decrypts && decrypts.length() > 0) {
                    JSONObject jsons = JSONObject.parseObject(decrypts);
                    System.out.println("jsons:: "+jsons.toString());
                    MemberUserDO UserDO= new MemberUserDO();
                    UserDO.setName(jsons.get("nickName").toString()); // 用户昵称
                    UserDO.setAvator(jsons.get("avatarUrl").toString()); // 用户头像
                    /*String gender = jsons.get("gender").toString();
                    if("2".equals(gender)){
                        UserDO.setSex(2);
                    }else {
                        UserDO.setSex(1);
                    }
                    UserDO.setCityId(jsons.get("city").toString()); // 城市
                    UserDO.setProvinceId(jsons.get("province").toString());// 省份*/
                    //如果有邀请码，设为上级
                    Object fatherCode = map.get("InvitationCode");
                    if (fatherCode != null && !fatherCode.toString().equals("")) {
                        MemberUserDO fatherUser = memberUserService.getByCode(fatherCode.toString());
                        UserDO.setIntroUser(fatherUser.getId());
                        UserDO.setIndirectUser(fatherUser.getIntroUser());
                    }
                    String userId = UuidUtil.get32UUID();
                    Date date = new Date();
                    UserDO.setId(userId);
                    UserDO.setWechatOpenId(openid);
                    //UserDO.setAuroraId(userId);
                    UserDO.setCreateAt(date);
                    UserDO.setUpdateAt(date);
                    UserDO.setDelFlag(0);
                    UserDO.setDisabled(0);
                    UserDO.setPostType(0);
                    UserDO.setLevel(0);
                    //得到不重复的邀请码
                    boolean T = false;
                    do {
                        Map userMap = new HashMap<String,Object>();
                        int code = (int)((Math.random() * 9 + 1) * 1000000);
                        String myshareCode = String.valueOf(code);
                        userMap.put("code",myshareCode);
                        List<MemberUserDO> MemberList = memberUserService.list(userMap);
                        if(MemberList.size()>0) {
                            T = false;
                        } else {
                            T = true;
                            UserDO.setCode(myshareCode);
                        }
                    } while (!T);
                    //UserDO.setWechat("");
                    if(memberUserService.save(UserDO)>0){
                        memberUserDO = UserDO;
                        log.error("微信授权登录结束，新用户："+memberUserDO.toString());
                        return R.ok().put("data", UserDO);
                    }

                } else {
                    return R.error("授权失败");
                }
            }
            log.error("微信授权登录结束，老用户："+memberUserDO.toString());
            return R.ok("登陆成功").put("data", memberUserDO);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("授权失败");
        }
    }

    /**
     * 获取token
     */
    @GetMapping("/getToken")
    @ResponseBody
    public R getToken(){
        try{
            String token = memberTokenService.getToken();
            return R.ok().put("data",token);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 我的推广
     */
    @PostMapping("/getExtension")
    @ResponseBody
    public R getExtension(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            return memberUserService.getExtension(params);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 反馈意见
     */
    @PostMapping("/feedBack")
    @ResponseBody
    public R feedBack(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("content") || !params.containsKey("content")
                ){
            return R.error("参数异常");
        }
        try{
            MemberFeedbackDO memberFeedbackDO = new MemberFeedbackDO();
            memberFeedbackDO.setId(UuidUtil.get32UUID());
            memberFeedbackDO.setDelFlag(0);
            memberFeedbackDO.setUserId(params.get("userId").toString());
            memberFeedbackDO.setContent(params.get("content").toString());
            memberFeedbackDO.setCreateAt(new Date());
            if (memberFeedbackService.save(memberFeedbackDO) == 1) {
                return R.ok();
            }
            return R.error();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 修改取货方式
     * postType  0:自提，1：快递
     */
    @PostMapping("/setPostType")
    @ResponseBody
    public R setPostType(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("postType") || !params.containsKey("postType")
                ){
            return R.error("参数异常");
        }
        try{
            String userId = params.get("userId").toString();
            int postType = Integer.valueOf(params.get("postType").toString());
            MemberUserDO userDO = new MemberUserDO();
            userDO.setId(userId);
            userDO.setPostType(postType);
            if (memberUserService.update(userDO) == 1) {
                return R.ok();
            }
            return R.error();
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 去签到
     */
    @PostMapping("/addSign")
    @ResponseBody
    public R addSign(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                ){
            return R.error("参数异常");
        }
        try{
            Date date = new Date();
            SimpleDateFormat sdf1 =new SimpleDateFormat("yyyy-MM-dd" );
            String str1 = sdf1.format(date);
            String userId = params.get("userId").toString();
            if (memberSignService.getTodaySign(userId).size() != 0) {
                return R.error("你今天已经签到过了");
            }
            return memberSignService.addSign(params);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }

    /**
     * 获取签到记录
     * month  需要请求的年月，比如  2019-07
     */
    @PostMapping("/getSignList")
    @ResponseBody
    public R getSignList(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId") || !params.containsKey("userId")
                || !params.containsKey("month") || !params.containsKey("month")
                ){
            return R.error("参数异常");
        }
        try{
            List<MemberSignDO> list = memberSignService.getSignList(params);
            return R.ok().put("data",list);
        }catch (Exception e){
            return R.error("服务器网络异常");
        }
    }




}
